const axios = require('axios');

const BASE_URL = 'http://localhost:9000';

async function testContactMsg() {
  console.log('开始测试contact_msg接口...\n');
  
  // 测试1: 正常请求
  console.log('测试1: 正常请求');
  try {
    const response = await axios.post(`${BASE_URL}/contact_msg`, {
      firstname: '测试',
      lastname: '用户',
      budget: '1000-5000',
      email: 'test@example.com',
      message: '这是一个测试消息'
    });
    
    console.log('✅ 正常请求成功:', response.data);
  } catch (error) {
    console.log('❌ 正常请求失败:', error.response?.data || error.message);
  }
  
  console.log('\n等待2秒...');
  await new Promise(resolve => setTimeout(resolve, 2000));
  
  // 测试2: 邮箱格式验证
  console.log('\n测试2: 邮箱格式验证');
  try {
    const response = await axios.post(`${BASE_URL}/contact_msg`, {
      firstname: '测试',
      lastname: '用户',
      budget: '1000-5000',
      email: 'invalid-email',
      message: '测试邮箱验证'
    });
    
    console.log('❌ 邮箱验证应该失败但成功了:', response.data);
  } catch (error) {
    if (error.response?.status === 400) {
      console.log('✅ 邮箱验证正确失败:', error.response.data);
    } else {
      console.log('❌ 邮箱验证失败但状态码不正确:', error.response?.data || error.message);
    }
  }
  
  console.log('\n测试3: 快速连续请求测试频率限制');
  for (let i = 1; i <= 6; i++) {
    console.log(`\n请求 ${i}/6:`);
    try {
      const response = await axios.post(`${BASE_URL}/contact_msg`, {
        firstname: `用户${i}`,
        lastname: '测试',
        budget: '1000-5000',
        email: `user${i}@example.com`,
        message: `测试消息 ${i}`
      });
      
      console.log(`✅ 请求 ${i} 成功:`, response.data.success);
    } catch (error) {
      if (error.response?.status === 429) {
        console.log(`✅ 请求 ${i} 被正确限制 (429):`, error.response.data.message);
      } else {
        console.log(`❌ 请求 ${i} 失败:`, error.response?.data || error.message);
      }
    }
    
    // 前5次快速请求，最后一次等待一下
    if (i < 5) {
      await new Promise(resolve => setTimeout(resolve, 100));
    }
  }
  
  console.log('\n测试完成！');
}

// 如果直接运行这个文件
if (require.main === module) {
  testContactMsg().catch(console.error);
}

module.exports = { testContactMsg };